import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.rmi.*;
import java.util.*;


/**
 * This is a simple example of an HTTP Servlet.  
 * and HEAD methods of the HTTP protocol.
 */
public class TestServletAndRMI2 extends HttpServlet
{ 
    String msg[] = {
	"1. HTTP server and the database server are running on 2 machines.",
	"2. A Java servlet is running on same machine as HTTP server",
	" and the servlet is executed by Java Servlet engine.",
	"3. An App. Server program is running on same machine as DB server.",
	" and it waits for call from any machine.",
	"4. The app. server will retrieves data from database when called.",
	"5. The servlet calls remote app. server to retrieve data and",
	" produces web page based on the data sent from remote app. server.", 
	    ""
    };
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) 
        throws ServletException, IOException {

	PrintWriter out;
	String title = "Demo: Servlet and the Remote Method Invocation<br>";
	// set content type and other response header fields first
	response.setContentType("text/html");
	// then write the data of the response
	out = response.getWriter();
	String sqlStr = (String) request.getParameter("sql");
	if ( sqlStr == null) sqlStr = "";
          
	out.println("<HTML><HEAD><TITLE>");
	out.println(title);
	out.println("</TITLE></HEAD><BODY bgcolor=#F0F5C0 ALIGN=center>");
	out.println("<H2 align=center>" + title + "</H2>");
	out.println("<H3 align=center>");
	out.println("<DIV align=center>");
	out.println("<FORM name=GetDATA METHOD=POST ACTION=/hwang/servlet/TestServletAndRMI2");
	out.println("<B>SQL Statement</B>");
	out.println("<input name=sql size=50 value=\"" + sqlStr + "\">");
	out.println("<input name=execute type=submit value=Run><BR>");
	try {
		// name of remote server object bound to rmi registry
		String serverObjectName = "//" + "cheval" + "/ChevalDBServer"; 

	// look remote object in rmiregistry
	System.err.println("Looking for remote server ...\n");
        ChevalDBServer dbObj=(ChevalDBServer) Naming.lookup( serverObjectName );
	sqlStr = request.getParameter("sql");
	Vector rows = dbObj.getResultSet(sqlStr);
	if ( rows == null || rows.size() < 0 ) {
		out.println("No data from the query!<BR>");
		return;
	}
	if ( rows.size() < 3 ) {
		out.println("No record received!");
		return;
	}
	DBRow row, lenRow = (DBRow) rows.remove(0); //cols' display lengths.
	int cols = lenRow.getColumnCount();
	float totalLen = 0.0f;
	for (int i = 0; i < cols; i ++)
		totalLen += Integer.parseInt(lenRow.getColumn(i));
	out.println("<BR><TABLE NOBORDER ALIGN=center>");
	Enumeration e = rows.elements();
	String s = null;
	int len, rowCnt = 1;
	out.print("<TR><TD COLSPAN=" + cols + " ALIGN=center bgcolor=#6666ff>");
	out.print("<font face=\"Arial,Helvetica,sans-serif\" size=3 color=#ffffff>");
	out.print("<B>Data Retrieved from App. Server and Presented by Servlet");
	out.print(" (" + (rows.size()- 1) + " records)");
	out.println("</B></TD></TR>");
	while ( e.hasMoreElements() ) {
		row = (DBRow) e.nextElement();
		out.print("<TR>");
		for ( int j = 0; j < cols; j++){
		    s = row.getColumn(j);
		    len = s.length();
		    if (rowCnt != 1)
				out.print("<TD bgcolor=#ccccff>");
		    else
			out.print("<TD bgcolor=#aaaaff width=" + Integer.parseInt(lenRow.getColumn(j))*8 +  "><B>");
		    if (rowCnt != 1) 
			if ( s.length() > 0 ) out.print(s);
		    	else out.print("-");
		    else out.print(s + "</B>");
		    out.print("</TD>");
		}
		out.println("</TR>");
		rowCnt++;
        }
	rows.clear();
	out.println("</TABLE>");
      }
      catch ( java.rmi.ConnectException ce ) {
         System.err.println( "Connection to server failed. " +
            "Server may be temporarily unavailable." ); }
      catch ( RemoteException e ) {
		System.err.println("Error in instantiating remote object\n" +
		e.toString() ); }
      catch ( Exception e ) { e.printStackTrace(); System.exit( 1 ); }      
            out.println("</H5></BODY></HTML>");
            out.close();
        }
    public void doGet(HttpServletRequest request,
                       HttpServletResponse response) 
        throws ServletException, IOException {
	PrintWriter out;
	String title = "Demo: Java Servlet Generated Web Page<br>";
	// set content type and other response header fields first
	response.setContentType("text/html");
	// then write the data of the response
	out = response.getWriter();

	out.println("<HTML><HEAD><TITLE>");
	out.println(title);
	out.println("</TITLE></HEAD><BODY bgcolor=#F0F5C0 ALIGN=center>");
	out.println("<H2 align=center>" + title + "</H2>");
	out.println("<H3 align=center>");
	out.println("The following features are domonstrated</H2>");
	out.println("<TABLE noborder align=center>");
	for ( int i = 0; i < msg.length; i++) {
		/*
		if( i % 2 == 0 ) out.println("<TR bgcolor=c0eae0><TD><B>");
		else out.println("<TR bgcolor=f0f5f0><TD><H3>");
		*/
		out.println("<TR><TD><H4>");
 		out.print(msg[i] + "</H4></TD></TR>");
	}
	out.println("</TABLE>");
	out.println("<DIV align=center>");
	out.println("<FORM name=GetDATA METHOD=POST ACTION=/hwang/servlet/TestServletAndRMI2>");
	out.println("<B>SQL Statement</B>");
	out.println("<input name=sql size=50 value=\"SELECT * FROM emp\">");
	out.println("<input name=execute type=submit value=Run>");
    }

}
